<?php
//4
function manage_chat_friend_list_page() {
    @$output = drupal_render(drupal_get_form('manage_chat_friend_list_form'));
    return $output;
}

function manage_chat_groups_edit_page($id){
    return drupal_get_form('manage_chat_groups_edit_form',$id);
}

function manage_chat_groups_add_page(){
    return drupal_get_form('manage_chat_groups_edit_form');
}

function manage_chat_friend_list_form($form, &$form_state)
{
    $form['employee_name'] = array(
        '#type' => 'textfield',
        '#prefix' =>'<div class="agent-search-form">',
        '#default_value' => '',
        '#attributes' => array('placeholder' => '姓名'),
        '#validated' => TRUE,
    );
    $form['phone'] = array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#attributes' => array('placeholder' => '电话'),
        '#maxlength' => 11,
        '#validated' => TRUE,
        '#suffix' =>'</div>',
    );
    $table['#markup'] = manage_chat_add_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}

function manage_chat_add_view_page($form, $form_state){
    global $user;
    $output = '';
    $header = array(
        array('data' => '选择', 'class' => ['no']),
        array('data' => '姓名', 'class' => ['employee_name']),
        array('data' => '操作', 'class' => ['cz']),
    );
    $rows = array();
    $query = db_select('employee', 'E')->extend('PagerDefault')->extend('TableSort');
    $query->join('department', 'D', 'E.department_id = D.department_id');
    $query->fields('E');
    $query->addField('D','department_name');
    if(!empty($form_state['values']['employee_name'])){
        $query->condition('E.employee_name', '%' . db_like($form_state['values']['employee_name']) . '%', 'LIKE');
    }
    if(!empty($form_state['values']['phone'])){
        $query->condition('E.phone', '%' . db_like($form_state['values']['phone']) . '%', 'LIKE');
    }
    $user_ids = get_existing_friends($user);
    if(!empty($user_ids)){
        $query->condition('E.employee_id', $user_ids, 'not in');
    }
    $query->limit(variable_get("list_page_item_number", 5));
    $result = $query->orderByHeader($header)->execute();

    $n = 1;
    foreach ($result as $row) {
        $rows[] = array(
            array('data' => '<input type="checkbox" class="listViewTableCheck" value ="' . $row->employee_id . '"/>' . $n++, 'class' => ['integrant essential no '.$row->employee_id]),
            array('data' => $row->employee_name."(".$row->department_name.")", 'class' => ['essential employee_name '.$row->employee_id]),
            array('data' => '<img width="25px" height="25px" src="'.base_path().'sites/all/themes/tweme/images/images/addFrid.png" style="cursor: pointer;" onclick="editfriend(\'add\',\''.$row->employee_id.'\',\''.$row->employee_name.'\',\'\')"/>', 'class' => 'cz '.$row->employee_id),
        );
    }
    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover'))));
    $output .= theme('pager');
    return $output;
}

function manage_chat_edit(){
    global $user;
    $user_info = _get_user_info($user->uid);
    $user_id = $_POST['user_id'];
    $chat_id = $_POST['chat_id'];
    $user_name = $_POST['user_name'];
    $group_id = $_POST['group_id'];
    $type = $_POST['type'];
    $ids = $_POST['ids'];
    $transaction = db_transaction();
    try{
        $isset_chat = isset_chat_user_load($user->uid,$user_id);
        if($type == 'add'){
            if(!$isset_chat){
                $chat_id = db_insert('chat')
                    ->fields(array(
                        'title' => $user->uid."&".$user_id,
                        'timestamp' => 0,
                        'type' => 0,
                        'active' => 1))
                    ->execute();
                $add_user = db_insert('chat_users')
                    ->fields(array(
                        'chat_id' => $chat_id,
                        'user_id' => $user->uid,
                        'nickname' => $user_info['name'],
                        'chat_group_id' =>1,
                        'active' => 1,
                        'checkpoint' => 0))
                    ->execute();
                $res1 = db_insert('chat_users')
                    ->fields(array(
                        'chat_id' => $chat_id,
                        'user_id' => $user_id,
                        'nickname' => $user_name,
                        'chat_group_id' =>1,
                        'active' => 1,
                        'checkpoint' => 0))
                    ->execute();
            }else{
                $upd_u =db_update('chat_users')
                    ->fields(array(
                        'active' => 1,
                    ))
                    -> condition('user_id',$user->uid, '=')
                    -> condition('chat_id',$isset_chat, '=')
                    ->execute();
                $upd_M =db_update('chat_users')
                    ->fields(array(
                        'chat_group_id' =>$group_id,
                    ))
                    -> condition('user_id',$user->uid, '=')
                    -> condition('chat_id',$isset_chat, '=')
                    ->execute();
            }
            $result = array('success' => 0, 'errorNum' => 0);
            echo json_encode($result);
        }else if($type == 'del'){
            $del_user = db_update('chat_users')
                ->fields(array(
                    'active' => 0
                ))
                -> condition('user_id',$user->uid, '=')
                -> condition('chat_id',$chat_id, '=')
                ->execute();
            $result = array('success' => 0, 'errorNum' => 0);
            echo json_encode($result);
        }else{
            $upd_M =db_update('chat_users')
                ->fields(array(
                    'chat_group_id' =>$group_id,
                ))
                -> condition('user_id',$user->uid, '=')
                -> condition('chat_id',$ids, 'in')
                ->execute();
            $result = array('success' => 0, 'errorNum' => 0);
            echo json_encode($result);
        }
    }catch (Exception $e){
        $transaction->rollback();
        $result = array('success' => 1, 'errorNum' => $e);
        echo json_encode($result);
    }
}


function get_existing_friends($user){
    $query = db_select('chat_users', 'CU');
        $query->join('chat', 'C', 'C.chat_id = CU.chat_id');
        $query->join('chat_users', 'CU1', 'CU.chat_id = CU1.chat_id');
        $query->condition('CU.user_id', $user->uid, '=');
        $query->condition('C.type', 0, '=');
        $query->condition('CU.active', '1', '=');
        $query->addField('CU1','user_id');
    $results = $query->execute()->fetchAll();
    foreach($results as $key => $value){
        $result[$value->user_id] = $value->user_id;
    }
    return $result;
}


function manage_chat_groups_edit_form($form, &$form_state) {
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = group_load($id);
        if (empty($record)) {
            drupal_set_message(t('数据不存在！'), 'status', FALSE);
            drupal_goto('manage_chat/groups/list');
        }
        $form_state['id'] = $id;
    }
    $form['group_name'] = array(
        '#type' => 'textfield',
        '#default_value' => !empty($record) ? $record->chat_group_name:'',
        '#validated' => TRUE,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($record) ? '修改' : '添加',
        '#access' => manage_chat_groups_edit_form_submit_access($form_state, $id),
    );
    return $form;
}

function manage_chat_groups_edit_form_validate(&$form, &$form_state) {
    if(empty($form_state['values']['group_name'])){
        form_set_error('group_name', '必须填写 聊天类别名称');
    }
}

function manage_chat_groups_edit_form_submit(&$form, &$form_state){
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (empty($id)) {
        $nid = db_insert('chat_groups') // Table name no longer needs {}
        ->fields(array(
            'chat_group_name' => $form_state['values']['group_name'],
            'user_id' => $user->uid,))
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
        }
    } else {
        $nid = db_update('chat_groups') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'chat_group_name' => $form_state['values']['group_name'],
            'user_id' => $user->uid,))
            -> condition('chat_group_id',$id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
    }
}

function manage_chat_groups_edit_form_submit_access(&$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;

    if ($id) {
        //edit
        $group = group_load($id);
        if ($group) {
            $user_info = _get_user_info($user->uid);
            if ($group ->user_id == $user->uid||$user_info['role'] === 'administrator') {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            //load false
            drupal_set_message(t('聊天类别数据不存在！'), 'status', FALSE);
            return FALSE;
        }
    } else {
        //add
        return user_access('manage chat');
    }
}

function group_load($id) {
    $result = db_select('chat_groups', 'CG')
        -> fields('CG')
        -> condition('CG.chat_group_id',$id, '=')
        -> execute()
        -> fetchObject();
    return $result;
}